<template>
  <div class="app-container">
    <el-card shadow="never">
      <template #header>
        <div class="card-header">
          <span>损耗管理</span>
        </div>
      </template>

      <div>
        <!-- 数量损耗表格 -->
        <el-divider content-position="left">数量损耗配置</el-divider>
        <el-table
          v-loading="loading"
          :data="quantityLossTableData"
          border
          style="width: 100%"
          max-height="400"
        >
          <el-table-column
            prop="quantity"
            label="数量(小于该数量时损耗为)"
            min-width="180"
            align="center"
          >
            <template #default="scope">
              <span>小于</span>
              <el-input-number
                v-model="scope.row.quantity"
                style="width: calc(100% - 100px)"
                :min="1"
                :precision="0"
                :step="1"
                size="small"
                @change="handleQuantityChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="lossPercentage" label="损耗比例%" min-width="160" align="center">
            <template #default="scope">
              <span>损耗为</span>
              <el-input-number
                v-model="scope.row.lossPercentage"
                style="width: calc(100% - 100px)"
                :min="0"
                :precision="1"
                :step="0.1"
                size="small"
                @change="handleLossChange"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template #default="scope">
              <el-button
                size="small"
                type="danger"
                link
                @click="handleDeleteQuantityRow(scope.$index, scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="mt-10px">
          <el-button size="small" type="primary" plain @click="handleAddQuantityRow">
            新增数量损耗
          </el-button>
        </div>

        <!-- 价格损耗表格 -->
        <el-divider content-position="left">价格损耗配置</el-divider>
        <el-table
          v-loading="loading"
          :data="priceLossTableData"
          border
          style="width: 100%"
          max-height="400"
        >
          <el-table-column
            prop="price"
            label="价格(小于该价格时损耗为)"
            min-width="180"
            align="center"
          >
            <template #default="scope">
              <span>小于</span>
              <el-input-number
                v-model="scope.row.price"
                style="width: calc(100% - 100px)"
                :min="0"
                :precision="2"
                :step="0.01"
                size="small"
                @change="handlePriceChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="lossPercentage" label="损耗比例%" min-width="160" align="center">
            <template #default="scope">
              <span>损耗为</span>
              <el-input-number
                v-model="scope.row.lossPercentage"
                style="width: calc(100% - 100px)"
                :min="0"
                :precision="1"
                :step="0.1"
                size="small"
                @change="handlePriceLossChange"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template #default="scope">
              <el-button
                size="small"
                type="danger"
                link
                @click="handleDeletePriceRow(scope.$index, scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <div class="mt-10px">
          <el-button size="small" type="primary" plain @click="handleAddPriceRow">
            新增价格损耗
          </el-button>
        </div>

        <div class="mt-20px text-center">
          <el-button type="primary" :loading="saving" @click="saveLossData">保存损耗数据</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import SysTextAPI from "@/api/system/sys-text.api";
import { useConfigStore } from "@/store/modules/config.store.js";

const configStore = useConfigStore();

defineOptions({
  name: "LossManagement",
  inheritAttrs: false,
});

// 数据相关
const quantityLossTableData = ref([]);
const priceLossTableData = ref([]);
const loading = ref(false);
const saving = ref(false);

// 获取损耗数据
const fetchLossData = async () => {
  try {
    loading.value = true;

    const response = await SysTextAPI.getTextByKey("price_loss_new");

    if (response) {
      const configData = JSON.parse(response);
      quantityLossTableData.value = configData.quantity || [];
      priceLossTableData.value = configData.price || [];

      // 保存到缓存
      configStore.savePriceLossCacheData(response);
    } else {
      // 如果没有数据，创建默认行
      const defaultData = {
        quantity: [
          { quantity: 10000, lossPercentage: 40 },
          { quantity: 15000, lossPercentage: 20 },
          { quantity: 999999, lossPercentage: 15 },
        ],
        price: [
          { price: 10000, lossPercentage: 10 },
          { price: 20000, lossPercentage: 5 },
          { price: 999999, lossPercentage: 2 },
        ],
      };

      quantityLossTableData.value = defaultData.quantity;
      priceLossTableData.value = defaultData.price;

      // 保存默认数据到缓存
      configStore.savePriceLossCacheData(JSON.stringify(defaultData));
    }
  } catch (error) {
    console.error("获取损耗数据失败:", error);
    ElMessage.error("获取损耗数据失败");

    // 创建默认数据
    const defaultData = {
      quantity: [
        { quantity: 10000, lossPercentage: 40 },
        { quantity: 15000, lossPercentage: 20 },
        { quantity: 999999, lossPercentage: 15 },
      ],
      price: [
        { price: 10000, lossPercentage: 10 },
        { price: 20000, lossPercentage: 5 },
        { price: 999999, lossPercentage: 2 },
      ],
    };

    quantityLossTableData.value = defaultData.quantity;
    priceLossTableData.value = defaultData.price;

    // 保存默认数据到缓存
    configStore.savePriceLossCacheData(JSON.stringify(defaultData));
  } finally {
    loading.value = false;
  }
};

// 处理数量变化
const handleQuantityChange = (_row) => {
  // 数量变化时自动排序
  quantityLossTableData.value.sort((a, b) => a.quantity - b.quantity);
};

// 处理价格变化
const handlePriceChange = (_row) => {
  // 价格变化时自动排序
  priceLossTableData.value.sort((a, b) => a.price - b.price);
};

// 处理损耗比例变化
const handleLossChange = () => {
  // 损耗比例变化时的处理逻辑
};

// 处理价格损耗比例变化
const handlePriceLossChange = () => {
  // 价格损耗比例变化时的处理逻辑
};

// 删除数量损耗行
const handleDeleteQuantityRow = async (index, _row) => {
  try {
    await ElMessageBox.confirm("确认删除这一行数量损耗数据吗？", "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    quantityLossTableData.value.splice(index, 1);
    ElMessage.success("删除成功");
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
    }
  }
};

// 删除价格损耗行
const handleDeletePriceRow = async (index, _row) => {
  try {
    await ElMessageBox.confirm("确认删除这一行价格损耗数据吗？", "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    priceLossTableData.value.splice(index, 1);
    ElMessage.success("删除成功");
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除失败:", error);
    }
  }
};

// 新增数量损耗行
const handleAddQuantityRow = () => {
  // 获取下一个合适的数量值
  const existingQuantities = quantityLossTableData.value
    .map((row) => row.quantity)
    .filter((qty) => qty > 0)
    .sort((a, b) => a - b);

  let nextQuantity = 1000; // 从1000开始

  // 找到第一个可用的数量值
  while (existingQuantities.includes(nextQuantity)) {
    nextQuantity += 1000;
  }

  // 添加新行
  const newRow = {
    quantity: nextQuantity,
    lossPercentage: 0,
  };

  quantityLossTableData.value.push(newRow);

  // 自动排序
  quantityLossTableData.value.sort((a, b) => a.quantity - b.quantity);

  ElMessage.success("新增数量损耗行成功，可直接编辑数量和损耗比例");
};

// 新增价格损耗行
const handleAddPriceRow = () => {
  // 获取下一个合适的价格值
  const existingPrices = priceLossTableData.value
    .map((row) => row.price)
    .filter((price) => price > 0)
    .sort((a, b) => a - b);

  let nextPrice = 1000; // 从1000开始

  // 找到第一个可用的价格值
  while (existingPrices.includes(nextPrice)) {
    nextPrice += 1000;
  }

  // 添加新行
  const newRow = {
    price: nextPrice,
    lossPercentage: 0,
  };

  priceLossTableData.value.push(newRow);

  // 自动排序
  priceLossTableData.value.sort((a, b) => a.price - b.price);

  ElMessage.success("新增价格损耗行成功，可直接编辑价格和损耗比例");
};

// 数据校验
const validateTableData = () => {
  const errors = [];
  const quantities = new Set();
  const prices = new Set();

  // 检查数量损耗表格是否为空
  if (quantityLossTableData.value.length === 0) {
    errors.push("数量损耗表格不能为空，请至少添加一行数据");
  }

  // 检查价格损耗表格是否为空
  if (priceLossTableData.value.length === 0) {
    errors.push("价格损耗表格不能为空，请至少添加一行数据");
  }

  // 校验数量损耗数据
  for (let i = 0; i < quantityLossTableData.value.length; i++) {
    const row = quantityLossTableData.value[i];
    const rowIndex = i + 1;

    // 检查数量
    if (!row.quantity || row.quantity <= 0) {
      errors.push(`数量损耗第${rowIndex}行：数量必须大于0`);
    }

    // 检查数量重复
    if (quantities.has(row.quantity)) {
      errors.push(`数量损耗第${rowIndex}行：数量${row.quantity}重复`);
    } else {
      quantities.add(row.quantity);
    }

    // 检查损耗比例
    if (row.lossPercentage < 0) {
      errors.push(`数量损耗第${rowIndex}行：损耗比例不能为负数`);
    }

    if (row.lossPercentage > 100) {
      errors.push(`数量损耗第${rowIndex}行：损耗比例不能超过100%`);
    }
  }

  // 校验价格损耗数据
  for (let i = 0; i < priceLossTableData.value.length; i++) {
    const row = priceLossTableData.value[i];
    const rowIndex = i + 1;

    // 检查价格
    if (!row.price || row.price <= 0) {
      errors.push(`价格损耗第${rowIndex}行：价格必须大于0`);
    }

    // 检查价格重复
    if (prices.has(row.price)) {
      errors.push(`价格损耗第${rowIndex}行：价格${row.price}重复`);
    } else {
      prices.add(row.price);
    }

    // 检查损耗比例
    if (row.lossPercentage < 0) {
      errors.push(`价格损耗第${rowIndex}行：损耗比例不能为负数`);
    }

    if (row.lossPercentage > 100) {
      errors.push(`价格损耗第${rowIndex}行：损耗比例不能超过100%`);
    }
  }

  return errors;
};

// 保存损耗数据
const saveLossData = async () => {
  try {
    saving.value = true;

    // 数据校验
    const validationErrors = validateTableData();
    if (validationErrors.length > 0) {
      const errorMessage = validationErrors.join("\n");
      ElMessageBox.alert(errorMessage, "数据校验失败", {
        confirmButtonText: "确定",
        type: "error",
        dangerouslyUseHTMLString: false,
      });
      return;
    }

    // 确认保存
    await ElMessageBox.confirm("确认保存损耗数据吗？保存后将更新服务器上的数据。", "确认保存", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 格式化数据为JSON字符串
    const configData = {
      quantity: quantityLossTableData.value,
      price: priceLossTableData.value,
    };

    // 调用API保存数据
    await SysTextAPI.saveOrUpdateTextByKey("price_loss_new", {
      fileKey: "price_loss_new",
      fileValue: JSON.stringify(configData),
    });
    await configStore.refreshPriceLossData();

    ElMessage.success("损耗数据保存成功");
  } catch (error) {
    if (error !== "cancel") {
      console.error("保存损耗数据失败:", error);
      ElMessage.error("保存损耗数据失败");
    }
  } finally {
    saving.value = false;
  }
};

// 组件挂载时获取损耗数据
onMounted(async () => {
  await fetchLossData();
});
</script>

<style scoped>
:deep(.el-input-number) {
  width: 100%;
}

:deep(.el-input-number .el-input__inner) {
  text-align: center;
}

:deep(.el-table td .el-input-number) {
  width: 100%;
}

:deep(.el-table td .el-input-number .el-input__inner) {
  text-align: center;
  padding: 0 5px;
}

.mt-10px {
  margin-top: 10px;
}

.mt-20px {
  margin-top: 20px;
}

.text-center {
  text-align: center;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
